package yagwl.service.fnd.flex;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import yagwl.service.fnd.flex.FlexAttributeEntity.Type;
import yagwl.service.util.db.DaoContext;
import yagwl.service.util.svc.BaseException;
import yagwl.service.util.svc.BaseException.ErrorCode;

public class FlexEntityDao {

  private static final Logger log = Logger.getLogger(FlexEntityDao.class
      .getName());

  private DaoContext ctx;

  public FlexEntityDao(DaoContext ctx) {
    this.ctx = ctx;
  }

  public FlexEntityEntity createExtEntity(FlexEntityEntity entity) {
    EntityManager em = ctx.em();
    try {/*
      for (FlexAttributeEntity attr : extEntity.getAttributes()) {
        em.getTransaction().begin();
        em.persist(attr);
        em.getTransaction().commit();
        extEntity.getAttributeIds().add(attr.getAttributeId());
      }*/

      em.getTransaction().begin();
      em.persist(entity);
      em.getTransaction().commit();
    } catch (Exception e) {
      log.severe(e.toString());
      em.getTransaction().rollback();
      throw new BaseException(ErrorCode.INTERNAL_TRANSACTION_ERROR, e);
    }
    return entity;
  }

  public FlexAttributeEntity getAttrType(Long attrTypeId) {
    EntityManager em = ctx.em();
    try {
      FlexAttributeEntity attrType = em.find(FlexAttributeEntity.class,
          attrTypeId);
      return attrType;
    } catch (Exception e) {
      log.severe(e.toString());
    }
    return null;
  }

  public FlexAttributeEntity createAttrType(String objectName, String attrCode,
      String attrName, Type attrValueType) {
    EntityManager em = ctx.em();
    FlexAttributeEntity attrType;
    try {
      em.getTransaction().begin();
      attrType = new FlexAttributeEntity();

      em.persist(attrType);
      em.getTransaction().commit();
    } catch (Exception e) {
      log.severe(e.toString());
      em.getTransaction().rollback();
      throw new BaseException(ErrorCode.INTERNAL_TRANSACTION_ERROR, e);
    }
    return attrType;
  }

  public List<FlexEntityEntity> getFlexEntities() {
    EntityManager em = ctx.em();
    Query q = em.createQuery("select from FlexEntityEntity");
    List<FlexEntityEntity> list = null;
    try {
      list = (List<FlexEntityEntity>) q.getResultList();
      for (@SuppressWarnings("unused") FlexEntityEntity e : list)
        ;
    } catch (Exception e) {
      log.severe(e.toString());
      list = new ArrayList<FlexEntityEntity>();
    }
    print(list);
    return list;
  }

  private void print(List<FlexEntityEntity> list) {
    log.fine("entities");
    for (FlexEntityEntity e : list)
      log.fine(e.getName());
  }

}
